#include <iostream>
#include <cstring>
using namespace std;

#include "DatabaseManager.h"
#include "UserManager.h"

UserManager::UserManager() : dbManager() {
    dbManager.connect();
}

UserManager::~UserManager() {
    dbManager.disconnect();
}

bool UserManager::registerUser(const string& username, const string& password) {
    lock_guard<mutex> lock(mutex);

    // 检查用户名是否已存在
    vector<string> results = dbManager.fetchResults("SELECT username FROM userinfo WHERE username = '" + username + "';");
    if (!results.empty()) {
        cerr << "Username already exists!" << endl;
        return false;
    }

    // 插入新用户
    string query = "INSERT INTO userinfo (username, password, role) VALUES ('" + username + "', '" + password + "', 'User');";
    if (dbManager.executeQuery(query)) {
        cout << "User registered successfully." << endl;
        return true;
    }
    return false;
}

bool UserManager::loginUser(const string& username, const string& password) {
    lock_guard<mutex> lock(mutex);

    // 获取用户信息
    vector<string> results = dbManager.fetchResults("SELECT id, password FROM userinfo WHERE username = '" + username + "';");
    if (results.empty()) {
        cerr << "User not found!" << endl;
        return false;
    }

    // 确保查询结果的字段顺序和内容正确
    if (results.size() < 2) {
        cerr << "Invalid query result!" << endl;
        return false;
    }

    int userId = stoi(results[0]);
    string storedPassword = results[1];

    // 比较输入的密码与存储的密码
    if (password == storedPassword) {
        users[userId] = User(userId, username, storedPassword, User::Role::User);  // 创建用户对象
        sessions[userId] = "active_session";  // 创建会话
        //cout << "logged in successfully." << endl;
        return true;
    } else {
        cerr << "Incorrect password!" << endl;
        return false;
    }
}


bool UserManager::deleteUser(const string& username) {
    lock_guard<mutex> lock(mtx);
    // 步骤1: 直接通过用户名删除数据库记录
    string deleteQuery = "DELETE FROM userinfo WHERE username = '" + username + "';";
    if (!dbManager.executeQuery(deleteQuery)) {
        cerr << "数据库删除失败: " << username << endl;
        return false;
    }
    // 步骤2: 清理内存中的用户数据
    int userIdToRemove = -1;
    for (const auto& userPair : users) {
        if (userPair.second.getUsername() == username) {
            userIdToRemove = userPair.first;
            break;
        }
    }
    if (userIdToRemove != -1) {
        users.erase(userIdToRemove);
        sessions.erase(userIdToRemove);
        cout << "内存数据已清理: " << username << endl;
    }
    cout << "用户 " << username << " 已彻底删除" << endl;
    return true;
}

User* UserManager::getUser(const string& username) {
    lock_guard<mutex> lock(mtx);
    
    // 遍历用户列表查找匹配的用户名
    for (auto& userPair : users) {
        if (userPair.second.getUsername() == username) {
            //cout << "Found user: " << username << endl;
            return &userPair.second;
        }
    }
    
    cerr << "User " << username << " not found!" << endl;
    return nullptr;
}